package com.lune.blog.auth.service;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.lune.blog.api.feign.UserServiceFeign;
import com.lune.blog.base.domain.LoginUser;
import com.lune.blog.base.domain.system.SysUser;
import com.lune.blog.base.exception.ServiceException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author yanjizhw@163.com
 * @date 2021/11/9 20:49
 * 描述:
 * @since 1.0.0
 */
@Service("adminLoginService")
public class AdminLoginServiceImpl {

    @Resource
    private UserServiceFeign userServiceFeign;

    public LoginUser login(String username, String password) {
        LoginUser loginUser = userServiceFeign.info(username).getData();
        SysUser sysUser = loginUser.getSysUser();
        if (!matchesPassword(password, sysUser.getPassword())) {
            throw new ServiceException("用户不存在/密码错误");
        }
        loginUser.setUserid(sysUser.getUserId());
        loginUser.setUsername(sysUser.getUsername());
        loginUser.setLoginTime(DateUtil.now());
        return loginUser;
    }

    /**
     * 判断密码是否相同
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    private boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }
}
